package org.example.work2.at.account.service.impl;

import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.example.work2.at.account.dto.Account;
import org.example.work2.at.account.mapper.AccountMapper;
import org.example.work2.at.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountMapper accountMapper;
	@Override
	public List<Account> findAllAccount() {
		return accountMapper.findAllAccount();
	}
	
	@Override
	public int insertAccount(Account account) {
		return accountMapper.insertAccount(account);
	}

	@Override
	public Account findAccountByCode(String accountCode) {
		return accountMapper.findAccountByCode(accountCode);
	}

	@Override
	@Transactional
	public boolean updateScores(Account account) throws Exception {
		Integer scores = account.getReduceScores();

		log.info("[updateScores] 当前 XID: {}", RootContext.getXID());
		log.info("[updateScores] 开始更新用户积分为：{}", scores);
		// 扣除积分
		int updateCount = accountMapper.reduceScores(account);
		// 扣除成功
		if (updateCount <= 0) {
			throw new Exception("扣除用户积分失败");
		}
		log.info("[updateScores] 扣除用户 {} 积分成功", scores);
		return true;
	}


}
